<?php


// 水印图类
class Water
{

    protected string $water;
    public function __construct(string $water)
    {
        $this->water = $water;
    }

    public function make(string $image, string $filename = null, $position = 1)
    {
        $this->checkImage($image);
        $res = $this->resource($image);
        // 生成水印图资源
        $water = $this->resource($this->water);
        // 生成水印到图片
        $position = $this->positions($res, $water, $position);
        imagecopy($res, $water, $position['x'], $position['y'], 0, 0, imagesx($water), imagesy($water));
        // 输出为图片
        return $this->show($image)($res, $filename ?? $image);
        // header('Content-type:image/jpeg');
        // return $this->show($image)($res);
    }

    protected function positions($image, $water, $position) {
        $info = ['x' => 0, 'y' => 0];
        switch ($position) {
            case 1: // 左上角
                break;
            case 2: // 上中间
                $info['x'] = (imagesx($image) - imagesx($water)) / 2;
                break;
            case 3: // 右上角
                $info['x'] = imagesx($image) - imagesx($water);
                break;
            case 4: // 左中间
                $info['y'] = (imagesy($image) - imagesy($water)) / 2;
                break;
            case 5: // 正中间
                $info['x'] =  (imagesx($image) - imagesx($water)) / 2;
                $info['y'] = (imagesy($image) - imagesy($water)) / 2;
                break;
            case 6: // 右下角
                $info['x'] =  imagesx($image) - imagesx($water);
                $info['y'] =  imagesy($image) - imagesy($water);
                break;
            default:
                break;
        }
        return $info;
    }

    protected function checkImage($image)
    {
        if (!is_file($image) || getimagesize($image) === false) {
            throw new Exception('file is not found');
        }
    }
    
    // 展示图片
    protected function show($image)
    {
        $info = getimagesize($image);
        $functions = [1 => 'imagegif', 2 => 'imagejpeg', 3 => 'imagepng'];
        return $functions[$info[2]];
    }
    // 创建图片资源 imagecreatefrompng('a.png')
    protected function resource($image)
    {
        $info = getimagesize($image);
        $functions = [1 => 'imagecreatefromgif', 2 => 'imagecreatefromjpeg', 3 => 'imagecreatefrompng'];
        return $functions[$info[2]]($image);
    }
}